from umqtt.simple import MQTTClient
import time
from config import MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT, MQTT_TOPIC

def connect_mqtt(data):
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT)
    try:
        start_send_time = time.ticks_ms()
        client.connect()
        client.publish(MQTT_TOPIC, data)
        end_send_time = time.ticks_ms()
        send_duration = end_send_time - start_send_time
        print(f"mqtt发送数据 taken: {send_duration} milliseconds")
        return client
    except Exception as e:
        print("Error connecting to MQTT server:", e)
        return None